package com.building18.handler.interceptors;


import com.alibaba.fastjson2.JSON;
import com.building18.pojo.User;
import jakarta.servlet.http.Cookie;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import jakarta.servlet.http.HttpSession;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import java.net.URL;
import java.net.URLDecoder;


/**
 * 自定义登录拦截器
 */
@Component
public class LoginInterceptor implements HandlerInterceptor {

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        System.out.println("请求到达拦截器！！！！");

        Object user= request.getSession().getAttribute("user");
        //有cookie
        if(user==null){
            Cookie[] cookies=request.getCookies();
            if(cookies != null){
                for(Cookie cookie:cookies){
                   if("user".equals(cookie.getName())){
                       //JSON ⇄ URL.encode ⇄ 类存储
                       String value=cookie.getValue();
                       String decode = URLDecoder.decode(value, "UTF-8");
                       user= JSON.parseObject(decode,User.class);
                       request.getSession().setAttribute("user",user);
                   }
                }
            }
        }

        //无cookie
        if(user==null){
            System.out.println("拦截到了登录请求，准备跳向登录页");

            // 设置响应内容类型为JSON，状态码为401
            response.setContentType("application/json;charset=UTF-8");
            response.setStatus(401);
            // 写入响应内容
            response.getWriter().write("{\"code\":401,\"msg\":\"未登录或登录已过期\"}");

            return false;
        }



        return true;
    }
}
